package com.pinyougou.cart.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.pinyougou.cart.service.CartService;
import com.pinyougou.pojogroup.Cart;
import entity.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Reference(timeout = 6000)
    private CartService cartService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    /**
     * 查询购物车
     *
     * @return
     */
    @RequestMapping("/findCartList")
    public List<Cart> findCartList() {


        //从cookie中提取本地购物车
        String cartListString = util.CookieUtil.getCookieValue(request, "cartList", "UTF-8");
        if (cartListString == null || cartListString.equals("")) {
            cartListString = "[]";

        }

        List<Cart> cartList_cookie =  JSON.parseArray(cartListString, Cart.class);

        //得到登陆人账号,判断当前是否有人登陆
        String username = SecurityContextHolder.getContext().getAuthentication().getName();

        if (username.equals("anonymousUser")) {//如果用户 未登录 查询cookie中购物车
            System.out.println("get cartList from cookie... " +username);
            return cartList_cookie;
        } else {//如果用户 已登录  查询合并购物车

            //从redis中读取购物车
            System.out.println("get cartList from redis... "+username);
            List<Cart> cartList_redis = cartService.findCartListFromRedis(username);

            if (cartList_cookie.size()>0){ //如果本地cookie中存在购物车
                //合并购物车
                cartList_redis = cartService.mergeCartList(cartList_redis, cartList_cookie);
                //清除本地cookie购物车
                util.CookieUtil.deleteCookie(request,response,"cartList");
                //将合并后的购物车存入redis
                cartService.saveCartListToRedis(username,cartList_redis);
            }
            return cartList_redis;
        }

    }

    /**
     * 添加商品到购物车
     *
     * @param itemId
     * @param num
     * @return
     */
    @RequestMapping("/addGoodsToCartList")
    public ResultInfo addGoodsToCartList(Long itemId, Integer num) {

        response.setHeader("Access-Control-Allow-Origin","http://localhost:9105");//可以访问的域
        response.setHeader("Access-Control-Allow-Credentials", "true");//允许使用cookie,不操作cookie则不需要加

        //得到登陆人账号,判断当前是否有人登陆
        String username = SecurityContextHolder.getContext().getAuthentication().getName();

        try {
            //2.调用服务方法操作购物车
            List<Cart> cartList = findCartList();
            cartList = cartService.addGoodsToCartList(cartList, itemId, num);

            if(username.equals("anonymousUser")){//如果用户 未登录
                //3.将新的购物车存入cookie
                util.CookieUtil.setCookie(request, response, "cartList", JSON.toJSONString(cartList), 3600 * 24, "UTF-8");
                System.out.println("save cartList to cookie... "+username);
            }else {//如果用户 已登录
                //3.将购物车保存到redis
                cartService.saveCartListToRedis(username,cartList);
                System.out.println("save cartList to redis... "+username);
            }

            return new ResultInfo(true, "添加购物车成功");

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultInfo(false, "添加购物车失败");
        }
    }

}
